<!-- 角色管理 -->
<template>
  <div class='roleManagement_container main_container'>
    <div style="height: 100%">
      <div class="search_form_box">
        <el-button class="addBtn" type="primary"  size="mini" @click="addShow">新增角色</el-button>

      </div>

      <div class="table_box">
        <materialTable :tableHead="tableHead" :tableData="tableList" ></materialTable>
      </div>

      <div>
        <pagination :tablePage="tablePage"></pagination>
      </div>

    </div>


    <!-- 新增弹窗 -->
    <el-dialog @open="openDialog" :modal-append-to-body="false" :close-on-click-modal="false" custom-class="add_dialog"  :title="dialog.title" :visible.sync="dialog.show" >
      <el-form v-if="dialog.title != '编辑角色权限'" ref="addForm" :rules="rules" :model="addForm"  label-position="right">
        <form-item
          label="角色名称"  
          model="roleName" 
          type="input" 
          :addForm="addForm"
        ></form-item>
        <form-item
          label="角色描述"  
          model="roleDescribe" 
          type="input" 
          :addForm="addForm"
        ></form-item>
        <form-item
          label="所属类型"  
          model="ownType" 
          type="radio"
          :radioList="ownTypeList"
          :addForm="addForm"
        ></form-item>
        <form-item
          label="角色类型 "  
          model="roleType" 
          type="radio"
          :radioList="roleTypeList1"
          v-if="addForm.ownType == 1"
          :addForm="addForm"
        ></form-item>
        <form-item
          label="角色类型 "  
          model="roleType" 
          type="radio"
          v-if="addForm.ownType == 2"
          :radioList="roleTypeList2"
          :addForm="addForm"
        ></form-item>
      </el-form>

      <el-form v-else :model="addForm" label-position="right" ref="addForm">
        <div v-for="(jtem,index) in editMenuList" :key="index">
          <div class="product_switch">
            <span>{{jtem.productName}}</span>
            <el-switch
              class="fr"
              v-model="jtem.switchBtn"
              @change="(e)=>{changeSwitch(e, index, jtem.productId)}"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </div>
          <el-tree
            :data="treeMenuList"
            :props="props"
            show-checkbox
            ref="tree"
            node-key="menuId"
            :default-checked-keys="checkedMenuKey"
            @check-change="handleCheckChange">
          </el-tree>
        </div>
      </el-form>
      
      <div slot="footer" class="dialog_footer">
        <el-button type="default" size="mini" @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" v-if="dialog.type == 'add'" @click="addSubmit" >保 存</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" v-if="dialog.type == 'update'" @click="updateSubmit">保 存</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" v-if="dialog.title=='编辑角色权限'" @click="editMenuSub" >确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import materialTable from "@/components/assembly/materialTable";
import pagination from "@/components/assembly/pagination";
import { createNamespacedHelpers } from "vuex";
let { mapActions } = createNamespacedHelpers("roleManagement");
export default {
  name: 'roleManagement',
  data() {
    return {
      loginIsAdmin: null,
      loginUserType: null,
      btnLoading: false,
      tableRowId: '',
      userId: "",
      tablePage: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      tableHead: {
        // order: true,
        setFunction: [
          {
            fun: this.updateShow,
            name: "编辑",
          },
          {
            fun: this.deleteShow,
            name: "删除",
          },
          {
            fun: this.editMenuShow,
            name: "权限"
          }
        ],
        data: [
          {
            name: "角色名称",
            key: "roleName",
          },
          {
            name: "角色描述",
            key: "roleDescribe",
          },
          {
            name: "所属类型",
            key: "ownType",
            filter: {
              1: '平台',
              2: '商家',
            }
          },
          {
            name: "角色类型",
            key: "roleTypeName",
          },
        ]
      },
      tableList: [],
      dialog: {
        show: false,
        title: '新增角色',
        type: 'add'
      },
      addForm: {
        roleName: '',
        roleDescribe: '',
        ownType: null,
        roleType: null,
      },
      props: {
        label: 'menuName',
        children: 'childrenMenu',
      },
      editMenuList: [],
      treeMenuList: [],
      checkedMenuKey: [],
      editMenuData: [],
      productIds: [],

      ownTypeList: [],
      roleTypeList1: [
        { value: 1, label: '平台' },
      ],
      roleTypeList2: [
        { value: 1, label: '一级商家' },
        { value: 2, label: '主体商家' },
        { value: 3, label: '二级商家' },
      ],

      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'change' }
        ],
        ownType: [
          { required: true, message: '请选择所属类型', trigger: 'change' }
        ],
      },
    }
  },

  watch: {
    
  },

  created() {
    this.jwtAuth = JSON.parse(localStorage.getItem("jwtAuth"));
    this.loginUserType = this.jwtAuth.userType
    this.loginIsAdmin = this.jwtAuth.extMap.isAdmin

    if(this.loginUserType == 1) {
      this.ownTypeList = [
        { value: 1, label: '平台' },
        { value: 2, label: '商家' },
      ]
    }else {
      this.ownTypeList = [
        { value: 2, label: '商家' },
      ]
    }
    this.initData();
  },

  mounted() {
    
  },
  

  methods: {
    ...mapActions(["post", "export", "formGet"]),

    initData(curPage) {
      let data = Object.assign(this.tablePage);
      data.siteId = this.siteId

      if(curPage) {
        data.curPage = curPage
      }
      
      this.post({
        API: 'pageList',
        data: data
      }).then(res => {
        this.tableList = res.data;
        this.tablePage = res.page;

        this.tableList.forEach(item => {
          switch (item.ownType) {
            case 1:
              item.roleTypeName = '平台'
              break;
          
            case 2:
              if(item.roleType == 1) {
                item.roleTypeName = '一级商家'
              }else if(item.roleType == 2) {
                item.roleTypeName = '主体商家'
              }else if(item.roleType == 3) {
                item.roleTypeName = '二级商家'
              }
              break;
          
            default:
              break;
          }
        })
      }).catch(err => {
        this.$message.error(err);
      })
    },

    handleCheckChange(data, checked, indeterminate) {
      // console.log(data, checked, indeterminate);
    },
    changeSwitch(bool, index, id) {
      if (this.editMenuList[index].dicMenuList.length == 0) {
        this.$message.error("请先添加此产品菜单");
        this.editMenuList[index].switchBtn = false;
        return false;
      }
      this.editMenuList[index].switchBtn = bool;
      if (bool) {
        this.productIds.push(id);
      } else {
        this.editMenuData[index] = [];
        this.productIds.forEach((item, index) => {
          if(item == id) {
            this.productIds.splice(index, 1);
          }
        })
      }
      this.$forceUpdate();
    },

    editMenuShow(rowData) {
      this.roleId = rowData.row.roleId;
      this.editMenuList = [];
      this.editMenuData = [];
      this.productIds = [];
      this.formGet({
        API: "editMenuShow",
        data: {
          roleId: this.roleId,
          isFilterChildren: 2
        }
      }).then(res => {
        this.dialog = {
          title: "编辑角色权限",
          show: true
        };

        this.editMenuList = res;
        this.treeMenuList = res[0].dicMenuList
        this.checkedMenuKey = res[0].menuIds


        /**  回显时，剔除所有父级id 👇👇👇👇👇👇👇 */
        if(this.checkedMenuKey && this.checkedMenuKey.length > 0) {
          let parentIds = [];
          this.treeMenuList.forEach(item => {
            if(item.childrenMenu) {
              parentIds.push(item.menuId);
            }

            if(item.childrenMenu && item.childrenMenu.length > 0) {
              item.childrenMenu.forEach(cItem => {
                if(cItem.childrenMenu && cItem.childrenMenu.length > 0) {
                  parentIds.push(cItem.menuId)

                  cItem.childrenMenu.forEach(jItem => {
                    if(jItem.childrenMenu && jItem.childrenMenu.length > 0) {
                      parentIds.push(jItem.menuId)
                    }
                  })
                }
              })
            }
          })


          for(let i=0; i<this.checkedMenuKey.length; i++) {
            for(let k=0; k<parentIds.length; k++) {
              if(this.checkedMenuKey[i] == parentIds[k]) {
                this.checkedMenuKey.splice(i, 1, 'flag');   // flag 占位符
              }
            }
          }

          if(this.checkedMenuKey.length > 0) {
            this.checkedMenuKey.filter(e => { return e!= 'flag' })
          }

        }
        /**  回显时，剔除所有父级id  👆👆👆👆👆👆 */



        for (let i in this.editMenuList) {
          this.editMenuList[i].switchBtn = JSON.parse(
            this.editMenuList[i].chooseProduct
          );

          if (this.editMenuList[i].switchBtn) {
            this.productIds.push(this.editMenuList[i].productId);
          }

          this.editMenuData.push([]);

          if (this.editMenuList[i].menuIds) {
            this.editMenuData[i] = this.editMenuList[i].menuIds;
          }
        }
      }).catch(err => {
        this.$message.error(err);
      });
    },

    editMenuSub() {
      this.btnLoading = true
      let haldCheckedIds = this.$refs.tree[0].getHalfCheckedKeys();
      // var menuids = this.$refs.tree[0].getCheckedKeys();
      var menuids = this.$refs.tree[0].getCheckedKeys().concat(haldCheckedIds);

      // console.log(menuids)
      // return false;

      // for (let i in this.editMenuData) {
      //   if (this.editMenuList[i].switchBtn) {
      //     if (this.editMenuData[i].length > 0) {
      //       menuids = menuids.concat(this.editMenuData[i]);
      //     } else {
      //       this.$message.error(
      //         "请选择" + this.editMenuList[i].productName + "下相应菜单"
      //       );
      //       return false;
      //     }
      //   }
      // }
      // console.log({
      //   ...{
      //     menuIds: menuids.join(","),
      //     productIds: this.productIds.join(",")
      //   },
      //   ...{ roleId: this.roleId }
      // });

      this.post({
        API: "editMenu",
        data: {
          ...{
            menuIds: menuids.join(","),
            productIds: this.productIds.join(",")
          },
          ...{ roleId: this.roleId }
        }
      })
        .then(res => {
          this.$message.success("编辑成功");
          this.dialog.show = false;
        })
        .catch(err => {
          this.$message.error(err);
        });
    },


    addShow() {
      this.dialog = {
        show: true,
        type: 'add',
        title: '新增角色'
      }
      this.addForm = {
        roleName: '',
        roleDescribe: '',
        ownType: null,
        roleType: null,
      }
    },

   addSubmit() {
      let data = Object.assign(this.addForm);
      data.siteId = this.siteId;

      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.post({
            API: 'insert',
            data: data
          }).then(res => {
            this.$message.success('新增成功');
            this.dialog.show = false;
            this.initData();
          }).catch(err => {
            this.$message.error(err);
            this.btnLoading = false;
          })
        } else {
          return false;
        }
      });
    },

    openDialog() {
      this.$nextTick(() => {
        this.resetForm();
      })
      this.btnLoading = false
    },

    updateShow(row) {
      this.dialog = {
        show: true,
        type: 'update',
        title: '编辑角色'
      }

      console.log(row.row.ownType)
      this.$nextTick(() => {
        this.addForm = JSON.parse(JSON.stringify(row.row))
      })
      this.addForm = JSON.parse(JSON.stringify(row.row))
    },

    updateSubmit() {
      let data = Object.assign(this.addForm);

      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.post({
            API: 'update',
            data: data
          }).then(res => {
            this.dialog.show = false;
            this.$message.success('修改成功');
            this.initData();
          }).catch(err => {
            this.$message.error(err);
            this.btnLoading = false;
          })
        } else {
          return false;
        }
      });
      
    },

    deleteShow(row) {
      this.tableRowId = row.row.roleId
      this.$confirm("是否确认删除", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning"
      }).then(() => {
        this.deleteSubmit();
      });
    },

    deleteSubmit() {
      this.formGet({
        API: 'delete',
        data: {
          id: this.tableRowId
        }
      }).then(res => {
        this.$message.success('删除成功');
        this.initData();
      }).catch(err => {
        this.$message.error(err);
      })
    },
    
    resetForm() {
      this.$refs.addForm.resetFields();
    },

  },

  components: {
    materialTable,
    pagination,
  }
}
</script>

<style scoped lang="less">

.product_switch {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

</style>